//
//  SCGoodsDetailController.m
//  shangcheng
//
//  Created by 张艳江 on 2019/5/31.
//  Copyright © 2019 张艳江. All rights reserved.
//

#import "SCGoodsDetailController.h"
#import "SCDetailSectionView.h"
#import "SDCycleScrollView.h"
#import "SCStoreSectionView.h"
#import "SCDetailFootView.h"
#import "SCGoodsAttributeController.h"
#import "SCIntegralOrderController.h"
#import "SCGoodsDetailCommentCell.h"
#import "SCAllEvaluaController.h"
#import "SCStoreController.h"

#import "UIViewController+XPSemiModal.h"

#import <WebKit/WebKit.h>

@interface SCGoodsDetailController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView      *headView;
@property (weak, nonatomic) IBOutlet UIView      *scrollBgView;
@property (weak, nonatomic) IBOutlet UILabel     *integralLab;
@property (weak, nonatomic) IBOutlet UILabel     *stockNumLab;
@property (weak, nonatomic) IBOutlet UILabel     *goodsTitleLab;
@property (weak, nonatomic) IBOutlet UILabel     *goodsInfoLab;
@property (weak, nonatomic) IBOutlet UILabel     *cartNumLab;//购物车里的数量
@property (weak, nonatomic) IBOutlet UILabel     *priceTagLab;
@property (weak, nonatomic) IBOutlet UIImageView *integralIcon;
@property (weak, nonatomic) IBOutlet UILabel     *jifenLab;
@property (weak, nonatomic) IBOutlet UILabel     *mkPriceLab;
@property (weak, nonatomic) IBOutlet UIButton    *bottomRightBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableView_top;

@property (strong, nonatomic) SCModel            *detailModel;
@property (strong, nonatomic) SCModel            *storeModel;
@property (strong, nonatomic) SCModel            *commentModel;
@property (strong, nonatomic) SDCycleScrollView  *cycleScrollView;
@property (strong, nonatomic) SCDetailFootView   *footView;
@property (strong, nonatomic) WKWebView          *webView;
@property (strong, nonatomic) UILabel            *titleLab;


@end

@implementation SCGoodsDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView_top.constant = -kTopHeight;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.backgroundColor = BGColor;
    self.headView.height = 453;
    [self.tableView registerNib:[UINib nibWithNibName:@"SCGoodsDetailCommentCell" bundle:nil] forCellReuseIdentifier:@"SCGoodsDetailCommentCellID"];
    
    if (self.isGiftApp != YES) {
        [self.bottomRightBtn setTitle:@"立即购买" forState:0];
    }
    //设置标题
    [self setUpTitleLable];
    //轮播图
    [self setUpScrollView];
    //请求数据
    [self requestDetailData];
}
- (void)setUpTitleLable{
    
    self.titleLab = [UILabel createLabelFrame:CGRectMake(0, 0, kScreenW/2, 30) text:@"商品详情" textColor:RGBA(51, 51, 51, 0) textAlignment:NSTextAlignmentCenter font:SCFont(16) numberOfLines:0];
    self.navigationItem.titleView = self.titleLab;
}
- (void)setUpScrollView{
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenW, kScreenW*4/6) delegate:nil placeholderImage:[UIImage imageWithColor:BGColor]];
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.currentPageDotColor = RGB(251, 30, 72);
    self.cycleScrollView.pageDotColor = [UIColor whiteColor];
    self.cycleScrollView.autoScrollTimeInterval = 3.0f;
    self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    [self.scrollBgView addSubview:self.cycleScrollView];
}
#pragma mark - 表格
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 && [self.commentModel.comment_count intValue] != 0) {
        return 1;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 116;
    }else{
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 73;
    }
    return 49;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        SCStoreSectionView *storeSectionView = [SCStoreSectionView addStoreSectionView];
        storeSectionView.model = self.storeModel;
        [storeSectionView.inStoreBtn addTarget:self action:@selector(clickInStoreBtn) forControlEvents:UIControlEventTouchUpInside];
        return storeSectionView;
    }else{
        SCDetailSectionView *sectionView = [SCDetailSectionView addSectionView];
        [sectionView.btn addTarget:self action:@selector(clickSeeMoreBtn) forControlEvents:UIControlEventTouchUpInside];
        if (section == 0) {
            if ([self.commentModel.comment_count intValue] == 0) {
                sectionView.titleLab.text = @"暂无商品评价";
                sectionView.btn.enabled = NO;
                sectionView.seeLab.hidden = YES;
                sectionView.jiantouImage.hidden = YES;
            }else{
                sectionView.titleLab.text = [NSString stringWithFormat:@"商品评价（%@）",self.commentModel.comment_count];
                sectionView.seeLab.hidden = NO;
                sectionView.jiantouImage.hidden = NO;
                sectionView.btn.enabled = YES;
            }
        }else{
            sectionView.titleLab.text = @"图文详情";
            sectionView.seeLab.hidden = YES;
            sectionView.jiantouImage.hidden = YES;
            sectionView.btn.enabled = NO;
        }
        return sectionView;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        SCGoodsDetailCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SCGoodsDetailCommentCellID"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.isGiftApp == YES) {
            cell.commentArray = self.commentModel.comment_list;
        }else{
            cell.commentArray = self.commentModel.commen_list;
        }
        return cell;
    }else{
        return nil;
    }
}

- (void)requestDetailData{
    
    NSString *type;
    NSString *url;
    if (self.isGiftApp == YES) {
        type = @"gift_id";
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftApp&a=App_gift"];
    }else{
        type = @"goods_id";
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsApp&a=goods_info"];
    }
    
    NSDictionary *dict = @{type:self.goodsId};
    //NSLog(@"----%@----%@",dict,url);
    [SVProgressHUD showWithStatus:@"加载中..."];
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        
        //NSLog(@"----%@",result);
        //商品详情数据
        if (self.isGiftApp == YES) {
            self.detailModel = [SCModel mj_objectWithKeyValues:result[@"data"][@"gift"]];
            self.integralLab.text = self.detailModel.payment_pure_integral;
            self.priceTagLab.hidden = YES;
            self.goodsTitleLab.text = self.detailModel.gift_name;
            self.stockNumLab.text = [NSString stringWithFormat:@"库存：%@件",self.detailModel.sku];
            self.goodsInfoLab.text = self.detailModel.intro;
        }else{
            self.detailModel = [SCModel mj_objectWithKeyValues:result[@"data"][@"goods_info"]];
            self.integralLab.text = self.detailModel.goods_price;
            self.integralIcon.hidden = YES;
            self.jifenLab.hidden = YES;
            self.goodsTitleLab.text = self.detailModel.goods_name;
            self.stockNumLab.text = [NSString stringWithFormat:@"库存：%@件",self.detailModel.stock];
            self.goodsInfoLab.text = self.detailModel.intro;
            self.mkPriceLab.text = self.detailModel.goods_mktprice;
        }
        
        NSArray *array = [self.detailModel.wap_pic componentsSeparatedByString:@";"];
        NSMutableArray *scrollImages = [NSMutableArray array];
        for (NSString *str in array) {
            NSString *imageStr = [NSString stringWithFormat:@"%@%@",Goods_ImageURL,str];
            [scrollImages addObject:imageStr];
        }
        self.cycleScrollView.imageURLStringsGroup = [scrollImages copy];
    
        [MyTool setRowHeightWithLabel:self.goodsTitleLab];
        CGFloat title_h = [MyTool getString:self.goodsTitleLab.text lineSpacing:5 font:SCFont(15) width:(kScreenW-24)];
        
        CGFloat info_h;
        if (self.goodsInfoLab.text.length > 0) {
            [MyTool setRowHeightWithLabel:self.goodsInfoLab];
            info_h = [MyTool getString:self.goodsInfoLab.text lineSpacing:5 font:SCFont(12) width:(kScreenW-24)];
        }else{
            info_h = 0;
        }
        self.headView.height = kScreenW*4/6+45+title_h+12+info_h+12+44;
        
        //店铺
        self.storeModel = [SCModel mj_objectWithKeyValues:result[@"data"][@"store"]];
        //评论
        if (self.isGiftApp == YES) {
            self.commentModel = [SCModel mj_objectWithKeyValues:result[@"data"][@"gift"][@"comment_info"]];
            self.commentModel.comment_list = [SCModel mj_objectArrayWithKeyValuesArray:self.commentModel.comment_list];
        }else{
            self.commentModel = [SCModel mj_objectWithKeyValues:result[@"data"][@"comment_info"]];
            self.commentModel.commen_list = [SCModel mj_objectArrayWithKeyValuesArray:self.commentModel.commen_list];
        }
        [self.tableView reloadData];
        //设置footView
        [self setupFootView];
    }];
}
#pragma mark - 设置footView
- (void)setupFootView{
    
    self.footView = [SCDetailFootView addDetailFootView];
    self.footView.frame = CGRectMake(0, 0, kScreenW, 0);
    self.footView.backgroundColor = [UIColor whiteColor];
    
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 0)];
    self.webView.opaque = NO;
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.scrollEnabled = NO;

    NSString *htmlStr = [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'>%@", self.detailModel.gift_content];
    htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"<img src=" withString:@"<p><img style='max-width: 100%' src="];
    //NSLog(@"---%@",htmlStr);
    [self.webView loadHTMLString:htmlStr baseURL:nil];
    
    //kvo 添加进度监控
    [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:NULL];
}
//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        if(self.webView.estimatedProgress >=1.0f) {
            [SVProgressHUD dismiss];
            [self.webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                CGFloat height = [result doubleValue];
                self.footView.height = height;
                self.webView.height = height;
                self.tableView.tableFooterView = self.webView;
                //NSLog(@"----%f",height);
            }];
        }
    }
}
#pragma mark - 去掉kvo
- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}
#pragma mark - 收藏或者进入购物车
- (IBAction)clickBtns:(UIButton *)sender {
    
    if (sender.tag == 0) {//收藏
        
    }else{//进入购物车
        ApplicationDelegate.tabBarVc.selectedIndex = 2;
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
#pragma mark - 查看更多评价
- (void)clickSeeMoreBtn{
    
    SCAllEvaluaController *vc = [[SCAllEvaluaController alloc]init];
    vc.goodsId = self.goodsId;
    if (self.isGiftApp == YES) {
        vc.type = @"gift_id";
        vc.url = @"admin.php?g=System&c=GiftApp&a=gift_comment";
    }else{
        vc.type = @"goods_id";
        vc.url = @"admin.php?g=System&c=GoodsApp&a=gift_comment";
    }
    [self.navigationController pushViewController:vc animated:YES];
}
//加入购物车/立即购买或者立即兑换
- (IBAction)clickBuyOrAddbtn:(UIButton *)sender {
    if (Token == nil) {
        [MyTool loginWithVc:self];
        return;
    }
    SCGoodsAttributeController *goodsAttributeVc = [[SCGoodsAttributeController alloc]init];
    goodsAttributeVc.isGiftApp = self.isGiftApp;
    goodsAttributeVc.productModel = self.detailModel;
    if (self.isGiftApp == YES) {
        goodsAttributeVc.product_id = self.detailModel.gift_id;
    }else{
        goodsAttributeVc.product_id = self.detailModel.goods_id;
    }
    WeakSelf;
    goodsAttributeVc.refreshCarNum = ^(NSString *product_id, NSString *buyNum, NSString *spec_desc) {
        if (product_id.length > 0) {//立即兑换/购买
            SCModel *model = [[SCModel alloc]init];
            if (self.isGiftApp == YES) {
                model.gift_id = product_id;
                model.gift_num = [buyNum intValue];
                model.cart_id = @"0";
            }else{
                model.goods_id = product_id;
                model.count = [buyNum intValue];
                model.spec = spec_desc;
                model.cart_id = @"0";
            }
            
            SCIntegralOrderController *vc = [[SCIntegralOrderController alloc]init];
            vc.goodsArray = @[model];
            vc.isGiftApp = self.isGiftApp;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }else{
            [weakSelf requestCartNum];
        }
    };
    XPSemiModalConfiguration *config = [XPSemiModalConfiguration defaultConfiguration];
    [self presentSemiModalViewController:goodsAttributeVc contentHeight:kScreenH - 250*kScale_H configuration:config completion:nil];
}
#pragma mark - 进入店铺
- (void)clickInStoreBtn{
    
    SCStoreController *vc = [[SCStoreController alloc]init];
    vc.title = self.storeModel.name;
    vc.store_id = self.storeModel.store_id;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - 滚动导航栏渐变
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    self.tableView.delegate = self;
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    self.cartNumLab.hidden = YES;
    if (Token != nil) {
        //获取购物车数量
        [self requestCartNum];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    UIColor * color = [UIColor whiteColor];
    CGFloat offsetY = scrollView.contentOffset.y;
    //NSLog(@"%f", offsetY);
    if (offsetY > 0){
        CGFloat alpha = MIN(1, 1 - ((kTopHeight - offsetY) / kTopHeight));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
        self.titleLab.textColor = RGBA(51, 51, 51, alpha);
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
        self.titleLab.textColor = RGBA(51, 51, 51, 0);
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.tableView.delegate = nil;
    [self.navigationController.navigationBar lt_reset];
}
#pragma mark - 获取购物车商品总数
- (void)requestCartNum{
    
    NSDictionary *dict = @{@"token":Token};
    NSString *url;
    if (self.isGiftApp == YES) {
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftCart&a=selectCount"];
    }else{
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsAppCart&a=selectCount"];
    }
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        //NSLog(@"----%@",result);
        SCModel *model = [SCModel mj_objectWithKeyValues:result[@"data"]];
        if (model.count != 0) {
            self.cartNumLab.hidden = NO;
            self.cartNumLab.text = [NSString stringWithFormat:@"%d",model.count];
        }
    }];
}

@end
